﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Microsoft.Diagnostics.Tracing;

using Sustainalytics.ESGRatings.BusinessLogic.Computing;
using Sustainalytics.ESGRatings.DataContract.ESG;
using Sustainalytics.ESGRatings.Computing.Service.Exceptions;
using Sustainalytics.ESGRatings.Computing.Service.Mappers;
using Serilog;
using System.Configuration;
using Sustainalytics.DataLayer.ConnectionStrings;
using Sustainalytics.Entities.ConnectionStrings;

namespace Sustainalytics.ESGRatings.Computing.Service.Controllers
{
    /// <summary>
    /// Tools controller.
    /// </summary>
    [RoutePrefix("api/v1/esgcompute")]
    public class ESGComputeController : ApiController
    {
        private readonly ComputationEngine engine;

        public ESGComputeController(ComputationEngine engine)
        {
            var clientPlatformConnectionString = ConfigurationManager.ConnectionStrings["ClientPlatform"].ConnectionString;

            var connectionStringsManager =
                ConnectionStringsManager.GetInstance(
                    ConnectionStringsRepository.GetInstance(clientPlatformConnectionString));

            var dwConnectionString = connectionStringsManager.GetConnectionString(ConnectionStringType.ClientDW);

            engine.SetConnectionString(dwConnectionString);

            this.engine = engine;
        }

        [Route("")]
        public HttpResponseMessage Post([FromBody]ESGRatingsOptionsDto options)
        {
            EventSource.SetCurrentThreadActivityId(Request.GetCorrelationId());

            if (options == null)
            {
                throw new InvalidInput("Invalid computation options");
            }

            {
                Stopwatch watch = new Stopwatch();
                watch.Start();

                var result = engine.ComputeESGRatings(options);
                
                watch.Stop();
                Log.Information($"computation elapsed {watch.ElapsedMilliseconds}");

                return Request.CreateResponse(HttpStatusCode.OK, result);
            }
        }

    }
}